﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DMU;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

namespace DMU.Gui
{
    public partial class ucBoMon : DevExpress.XtraEditors.XtraUserControl
    {
        private bool them=true;
        private DataTable dtBM;

        help hp = new help();
        Service sv = new Service();

        public ucBoMon()
        {
            InitializeComponent();
        }

        private void clickGrid()
        {
            int d = gridView1.FocusedRowHandle;
            if (d >= 0 && !them)
            {
                txtMa.Text = gridView1.GetRowCellValue(d, "MaBM").ToString();
                txtTen.Text = gridView1.GetRowCellValue(d, "TenBM").ToString();

                txtGhiChu.Text = gridView1.GetRowCellValue(d, "GhiChu").ToString();
                chkActive.Checked = bool.Parse(gridView1.GetRowCellValue(d, "IsActive").ToString());
                txtTen.Focus();
            }
            else
                txtMa.Text = txtTen.Text = "";
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.IsGetData)
                e.Value = e.ListSourceRowIndex + 1;
        }

        private SqlParameter[] getpara(string ma, string ten, string ghiChu, bool active)
        {
            SqlParameter[] pr = new SqlParameter[5];
            pr[0] = new SqlParameter("MaBM0", ma);
            pr[1] = new SqlParameter("TenBM0", ten);
            pr[2] = new SqlParameter("GhiChu0", ghiChu);
            pr[3] = new SqlParameter("IsActive0", active);
            pr[4] = new SqlParameter("MaTruong0", Service.info[4]);
            return pr;
        }

        private string[] getInfo()
        {
            string[] st = new string[4];
            st[0] = txtMa.Text;
            st[1] = txtTen.Text;
            st[2] = txtGhiChu.Text;
            st[3] = chkActive.Checked.ToString();
            return st ;
        }
        

        private void btnHoanTat_Click(object sender, EventArgs e)
        {
            
            if (!dxValidationProvider2.Validate())
            {
                if (cbbPath.Text == "")
                {
                    cbbPath.Focus(); return;
                }
                if (cbbSheetName.Text == "")
                {
                    cbbSheetName.Focus(); return;
                }
            }
            DataTable dt = sv.excelToDatatable(cbbPath.Text, "select MaBM,TenBM,GhiChu from [" + cbbSheetName.Text + "]");

            DataColumn cl = new DataColumn("IsActive", Type.GetType("System.Boolean"));
            dt.Columns.Add(cl);

            SqlParameter[] pr;
            int rowB = dt.Rows.Count; int d = 0;
            if (rowB > 0)
            {
               try
                {
                    sv.openConnect();
                    foreach (DataRow row in dt.Rows)
                    {
                        if (row["MaBM"] != null && row["MaBM"].ToString().Trim() != "" && row["TenBM"] != null && row["TenBM"].ToString().Trim() != "")
                        {
                            pr = getpara(row[0].ToString(), row[1].ToString(), row[2].ToString(), true);

                            if (sv.cusTomExecuteNonqueryStore("dmu_proBMThem1", pr))
                            {
                                row["IsActive"] = true;
                                d++;
                                try
                                {
                                    dtBM.ImportRow(row);
                                }
                                catch (Exception) { continue; }

                            }
                        }
                    }

                    sv.closeConnect();
                    dt.Dispose();

                    gridControl1.DataSource = dtBM;
                    hp.showMes("Import thành công " + d + "/" + rowB, -1);
                }
                catch (Exception et)
                {
                    hp.showMes("Import dữ liệu không thành công ! " + et.Message, 1);
                }
            }
            else
                hp.showMes("Dữ liệu trống ! Kiểm tra lại file ", -1);

        }

        private void ucBoMon_Load(object sender, EventArgs e)
        {
            dtBM = new DataTable();

            DataColumn[] cl=new DataColumn[4];
            cl[0]=new DataColumn("MaBM",Type.GetType("System.String"));
            cl[1] = new DataColumn("TenBM", Type.GetType("System.String"));
            cl[2]=new DataColumn("GhiChu",Type.GetType("System.String"));
            cl[3] = new DataColumn("IsActive", Type.GetType("System.Boolean"));

            dtBM.Columns.AddRange(cl);

            DataColumn[] c = new DataColumn[1];
            c[0] =dtBM.Columns["MaBM"];
            dtBM.PrimaryKey = c;
            gridControl1.DataSource = dtBM;
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            
            if (!dxValidationProvider1.Validate())
            {
                if (txtMa.Text == "")
                {
                    txtMa.Focus(); return;
                }
                if (txtTen.Text == "")
                {
                    txtTen.Focus(); return;
                }

            }

            try
            {
                SqlParameter[] pr = getpara(txtMa.Text, txtTen.Text, txtGhiChu.Text, chkActive.Checked);
                if (them)
                {
                    if (sv.executeScalarStore("dmu_proBMThem", pr) == "1")
                    {
                        sv.addRow(dtBM, getInfo());
                        txtMa.Text = txtTen.Text = "";
                        txtMa.Focus();
                    }
                    else
                    {
                        hp.showMes("Mã này đã tồn tại ! ", 1); txtMa.Focus();
                    }
                }
                else
                {
                    if (sv.executeNonqueryStore("dmu_proBMSuu",pr))
                    {
                        sv.updateRow(dtBM.Rows[this.BindingContext[dtBM].Position], getInfo());
                        hp.showMes("Thao tác thành công !", -1);
                    }

                    else
                        hp.showMes("Thao tác không thành công !. Kiểm tra lại dữ liệu", -1);
                }
            }
            catch (Exception et)
            {
                hp.showMes("Thao tác không thành công !. Kiểm tra lại dữ liệu " + et.Message, 1);
            }
        }

        private void chkThem_CheckedChanged(object sender, EventArgs e)
        {
            
            if (chkThem.Checked)
            {
                txtMa.Focus(); them = true;
                txtMa.Properties.ReadOnly = false;
            }
            else
            {
                them = false;
                txtMa.Properties.ReadOnly = true;
                clickGrid();
                txtTen.Focus();
            }
        }

        private void btnXoaBM_Click(object sender, EventArgs e)
        {
            int[] a = gridView1.GetSelectedRows();
            if (a.Length > 0)
            {
                if (hp.showMes(a.Length + " đối tượng sẽ bị xóa ?", 2) == DialogResult.Yes)
                {
                    sv.openConnect();
                    int d = 0;
                    
                    for (int i = 0; i < a.Length; i++)
                    {
                        if(gridView1.GetRowCellValue(a[i], "MaBM")!=null)
                            if (sv.cusTomExecuteScalarStore("dmu_proBMXoa", new SqlParameter("MaBM0", gridView1.GetRowCellValue(a[i], "MaBM").ToString()))!="1")
                            { gridView1.UnselectRow(a[i]); d++; }

                    }
                    gridView1.DeleteSelectedRows();
                    if (d > 0)
                        hp.showMes(d + " đối tượng không thể xóa. Vì nó đang được tham chiếu.", -1);
                }
            }
            else
                hp.showMes("Chọn dòng để thực hiện chức năng này !", -1);
        }

        private void loadDữLiệuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                dtBM = sv.getDatatable("dmu_proBMLoadData", null);
                gridControl1.DataSource = dtBM;
            }
            catch (Exception)
            {
                hp.showMes("Có lỗi vui lòng thử lại !! ", 1);
            }
        }

        private void cbbPath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            string path = hp.openFile();
            if (path != "")
            {
                try
                {
                    cbbPath.Text = path;
                    cbbSheetName.Properties.Items.Clear();
                    cbbSheetName.Properties.Items.AddRange(sv.getEcelSheetName(path));
                    cbbSheetName.Focus();
                }
                catch (Exception et) { hp.showMes("Lỗi khi load sheetName. Vui lòng thử lại ! " + et.Message, 1); }
            }
        }

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            clickGrid();
        }

        private void txtMa_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                EventArgs et = new EventArgs();
                btnLuu_Click(sender, et);
            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            clickGrid();
        }

        

    }
}
